<template>
    <div class="elderly-manage">
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>
                    <i class="iconfont icon-laoren"></i>&nbsp;老人管理
                </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <div class="handle-box">
                <el-input v-model="query.oldmanName" placeholder="老人姓名" class="handle-input mr10" clearable @change="handleSearch"></el-input>
                <el-input v-model="query.nurseName" placeholder="护工姓名" class="handle-input mr10" clearable @change="handleSearch"></el-input>
                <el-select v-model="query.nursingLevel" placeholder="请选择护工等级" class="handle-input mr10" clearable @change="handleSearch">
                    <el-option
                            v-for="item in nurseLevelList"
                            :key="item"
                            :label="item"
                            :value="item">
                    </el-option>
                </el-select>
                <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
                <el-button type="primary" icon="el-icon-plus" @click="handleAdd">新增</el-button>
                <el-button
                        type="primary"
                        icon="el-icon-delete"
                        class="handle-del mr10"
                        @click="delAllSelection"
                >批量删除</el-button>
            </div>
            <el-table
                    :data="tableData"
                    border
                    class="table"
                    ref="multipleTable"
                    :height="tableHeight"
                    header-cell-class-name="table-header"
                    @selection-change="handleSelectionChange"
            >
                <el-table-column type="selection" align="center"></el-table-column>
                <el-table-column type="index" label="序号" width="55" align="center" :index='(index)=>{return (index+1) + (query.currentPage-1)*query.pageSize }'></el-table-column>
                <el-table-column prop="oldmanName" label="姓名" align="center" min-width="80px"></el-table-column>
                <el-table-column prop="oldmanSex" label="性别" align="center" min-width="80px"></el-table-column>
                <el-table-column prop="oldmanAge" label="年龄" align="center" min-width="80px"></el-table-column>
                <el-table-column prop="oldmanCardId" label="身份证号" align="center" min-width="200px"></el-table-column>
                <el-table-column prop="isMarried" label="婚否" align="center" min-width="80px"></el-table-column>
                <el-table-column prop="politics" label="政治面貌" align="center" min-width="80px">
                    <template slot-scope="scope">
                        <div  v-if="scope.row.politics == '党员'">
                            <i class="iconfont icon-dangyuan" style="font-size: 13px;"></i>
                            {{ scope.row.politics }}
                        </div>
                        <div v-else-if="scope.row.politics == '团员'">
                            <i class="iconfont icon-tuanyuan" style="font-size: 13px;"></i>
                            {{ scope.row.politics }}
                        </div>
                        <div v-else>
                            <i class="iconfont icon-qunzhong" style="font-size: 18px;"></i>
                            {{ scope.row.politics }}
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="userName" label="联系人" align="center" min-width="80px"></el-table-column>
                <el-table-column prop="nurseName" label="护工" align="center" min-width="80px"></el-table-column>
                <el-table-column prop="nursingLevel" label="护工等级" align="center" min-width="80px"></el-table-column>
                <el-table-column label="操作" width="150" align="center">
                    <template slot-scope="scope">
                        <el-button
                                type="text"
                                icon="el-icon-edit"
                                @click="handleEdit(scope.$index, scope.row)"
                        >修改</el-button>
                        <el-button
                                type="text"
                                icon="el-icon-delete"
                                @click="handleDelete(scope.$index, scope.row)"
                        >删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination
                        background
                        layout="-> ,sizes , prev, pager, next"
                        :current-page="query.currentPage"
                        :page-size="query.pageSize"
                        :total="pageTotal"
                        @current-change="handlePageChange"
                        @size-change="handleSizeChange"
                        :page-sizes="[10, 20, 50, 100]"
                ></el-pagination>
            </div>
        </div>

        <!-- 编辑弹出框 -->
        <el-dialog :title="dialogTitle" v-dialogDrag :visible.sync="editVisible" width="555px">
            <el-form ref="form" :model="form" label-position="left" label-width="90px" :rules="rules">
                <el-form-item label="老人姓名" prop="oldmanName">
                    <el-input v-model="form.oldmanName" maxlength="5" show-word-limit></el-input>
                </el-form-item>
                <el-form-item label="老人性别" prop="oldmanSex">
                    <el-radio v-model="form.oldmanSex" label="男">男</el-radio>
                    <el-radio v-model="form.oldmanSex" label="女">女</el-radio>
                </el-form-item>
                <el-form-item label="老人年龄" prop="oldmanAge">
                    <el-input-number v-model="form.oldmanAge" controls-position="right" :min="1"></el-input-number>
                </el-form-item>
                <el-form-item label="身份证号" prop="oldmanCardId">
                    <el-input v-model="form.oldmanCardId" maxlength="18" show-word-limit></el-input>
                </el-form-item>
                <el-form-item label="婚否" prop="isMarried">
                    <el-radio v-model="form.isMarried" label="已婚">已婚</el-radio>
                    <el-radio v-model="form.isMarried" label="未婚">未婚</el-radio>
                </el-form-item>
                <el-form-item label="政治面貌" prop="politics">
                    <el-radio-group v-model="form.politics">
                        <el-radio label="党员"></el-radio>
                        <el-radio label="团员"></el-radio>
                        <el-radio label="群众"></el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="联系人" prop="oldmanParentId">
                    <el-select v-model="form.oldmanParentId" filterable placeholder="请选择">
                        <el-option
                                v-for="item in parentList"
                                :key="item.id"
                                :label="item.userName"
                                :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>

                <div class="group-title">
                    <span>护工信息</span>
                </div>
                <el-form-item label="护工姓名" prop="nurseId">
                    <el-select v-model="form.nurseId" filterable placeholder="请选择">
                        <el-option
                                v-for="item in nurseList"
                                :key="item.id"
                                :label="item.nurseName"
                                :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="护理等级" prop="nursingLevel">
                    <el-radio-group v-model="form.nursingLevel">
                        <el-radio label="初级"></el-radio>
                        <el-radio label="中级"></el-radio>
                        <el-radio label="高级"></el-radio>
                    </el-radio-group>
                </el-form-item>

            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="saveEdit">确 定</el-button>
                <el-button @click="editVisible = false">取 消</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
    import { fetchData } from '../../api/index';
    export default {
        data() {

            var oldmanName = (rule, value, callback) => {
                const reg = /[\u4e00-\u9fa5]/gm;
                if (!reg.test(value)) {
                    return callback(new Error('老人姓名不能含有英文、数字、特殊字符'));
                } else {
                    callback();
                }
            };

            var oldmanCardId = (rule, value, callback) => {
                const reg = /^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[Xx])$)$/;
                if (!reg.test(value)) {
                    return callback(new Error('身份证号格式错误'));
                } else {
                    callback();
                }
            };

            var oldmanParentId = (rule, value, callback) => {
                if (!value) {
                    return callback(new Error('联系人不能为空'));
                } else {
                    callback();
                }
            };

            return {
                query               : {
                                          oldmanName : '',
                                          nurseName : '',
                                          nursingLevel : '',
                                          currentPage : 1,
                                          pageSize : 10
                                      },
                tableData           : [],
                multipleSelection   : [],
                delList             : [],
                editVisible         : false,
                pageTotal           : 0,
                form                : {
                                          oldmanName : '',
                                          oldmanSex : '男',
                                          oldmanAge : 60,
                                          oldmanCardId : '',
                                          isMarried : '已婚',
                                          politics : '群众',
                                          oldmanParentId : '',
                                          nurseId : '',
                                          nursingLevel : '中级',
                                      },
                tableHeight         : document.documentElement.clientHeight-350,    // 表格高度
                rules               : {
                    oldmanName     : [{ required: true, validator: oldmanName, trigger: 'blur' }],
                    oldmanSex      : [{ required: true}],
                    oldmanAge      : [{ required: true}],
                    oldmanCardId   : [{ required: true, validator: oldmanCardId, trigger: 'blur' }],
                    isMarried      : [{ required: true}],
                    politics       : [{ required: true}],
                    oldmanParentId : [{ required: true, validator: oldmanParentId, trigger: 'blur' }],
                },
                parentList          : [],
                nurseList           : [],
                dialogTitle         : "",
                nurseLevelList      : ['初级','中级','高级'],
            };
        },
        watch :{
            /**
             * 监听新增/编辑 弹窗关闭 重置表单数据
             * @param   nv 新值
             * @param   ov 之前值
             */
            editVisible(nv,ov){
                if(!nv){
                    // 重置表单数据
                    this.$refs.form.resetFields();

                    console.log(this.form)
                    /**
                     * 由于from点id未被表单绑定，当表单清空时，id不能及时清空，需要手动清除
                     */
                    if(this.form.id){
                        delete this.form.id;
                    };
                }
            },
        },
        methods: {
            /**
             * 获取表格数据
             */
            getData() {
                this.$api.getOlders( this.query ).then((res)=>{
                    this.tableData = res.data;
                    this.pageTotal = res.total;
                })
            },

            /**
             * 触发搜索按钮
             */
            handleSearch() {
                this.$set(this.query, 'currentPage', 1);
                this.getData();
            },

            /**
             * 删除操作
             */
            handleDelete(index, row) {
                // 二次确认删除
                this.$confirm(`确定要删除 ${row.oldmanName} 用户的信息吗？`, '提示', {
                    type: 'warning',
                    center: true
                }).then(() => {
                    this.$api.deleteOlder([
                        row.id
                    ]).then((res)=>{
                        this.$message.success('删除成功');
                        this.getData();
                    })
                }).catch(() => {});
            },

            /**
             * 多选操作
             */
            handleSelectionChange(val) {
                this.multipleSelection = val;
            },

            /**
             * 删除选中数据
             */
            delAllSelection() {
                let length = this.multipleSelection.length,
                    arr    = [];

                // 没有选择项直接结束
                if (!length) return;

                for (let i = 0; i < length; i++) {
                    arr.push(this.multipleSelection[i].id);
                };

                this.$api.deleteOlder(arr).then((res)=>{
                    this.$message.success('删除成功');
                    this.multipleSelection = [];
                    this.getData();
                })
            },

            /**
             * 新增操作
             */
            handleAdd(){
                this.dialogTitle = "新增老人信息";
                this.editVisible = true;
                console.log(this.form)
            },

            /**
             * 编辑操作
             */
            handleEdit(index, row) {
                this.dialogTitle = "编辑老人信息";
                this.editVisible = true;

                // this.$nextTick()将赋值操作放到dom渲染结束之后
                this.$nextTick(() => {
                    this.form = JSON.parse(JSON.stringify(row));
                })
            },

            /**
             * 保存编辑
             */
            saveEdit() {
                this.$refs.form.validate(valid => {
                    if (!valid) {
                        return this.$message({
                            message: '请核对填写信息',
                            type: 'error'
                        });
                    };

                    this.$api.updateOlder(this.form).then((res)=>{
                        if( this.form.id ){
                            this.$message.success("修改老人信息成功");
                        }else {
                            this.$message.success("新增老人信息成功");
                        };
                        this.editVisible = false;
                        this.handleSearch();
                    });
                });
            },

            /**
             * 分页导航 改变展示页
             */
            handlePageChange(val) {
                this.$set(this.query, 'currentPage', val);
                this.getData();
            },

            /**
             * 分页导航 改变展示数量
             * @param index
             */
            handleSizeChange(index) {
                this.$set(this.query, 'pageSize', index);
                this.getData();
            },

            /**
             * 加载页面基本数据
             */
            loadBasicData() {

                // 获取家属列表
                this.$api.getAllUsers().then((res)=>{
                    this.parentList = res.data;
                });

                // 获取护工列表
                this.$api.getAllNurses().then((res)=>{
                    this.nurseList = res.data;
                });
            },

        },
        beforeMount() {

            // 加载初始数据
            this.getData();
            this.loadBasicData();

        }
    };
</script>

<style lang="less">

</style>
